package com.aishua.fire.config.jwtsecurity.login;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;  
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;  
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import com.aishua.fire.common.CookieUtils;
import com.aishua.fire.common.JsonFormatUtil;
import com.aishua.fire.common.JsonObjectResult;
import com.aishua.fire.common.constant.HeaderConstants;
import com.aishua.fire.common.eenum.WhiteInterfaceEnum;
import com.aishua.fire.common.req.BodyReaderHttpServletRequestWrapper;
import com.aishua.fire.common.req.HttpHelper;
import com.aishua.fire.config.init.Init;
import com.aishua.fire.entity.account.Session;
import com.aishua.fire.mapper.LoginMapper;
import com.alibaba.fastjson.JSON;

import javax.servlet.FilterChain;  
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;  
  
/** 
 * token的校验 
 * 该类继承自BasicAuthenticationFilter，在doFilterInternal方法中， 
 * 从http头的Authorization 项读取token数据，然后用Jwts包提供的方法校验token的合法性。 
 * 如果校验通过，就认为这是一个取得授权的合法请求 
 * @author zhaoxinguo on 2017/9/13. 
 */  
@Slf4j
@Component
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {  
  

	@Autowired
	private LoginMapper loginMapper;
	
	private static final String FILTER_APPLIED = "__spring_security_demoFilter_JWTAuthenticationFilter";
	
    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);  
        log.info("JWTAuthenticationFilter.JWTAuthenticationFilter构造进来了");
    }  
  
    @SuppressWarnings("rawtypes")
    @Override  
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException{
    	if (request.getAttribute(FILTER_APPLIED) != null) {
    		UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(null, null, new ArrayList<SimpleGrantedAuthority>());
			SecurityContextHolder.getContext().setAuthentication(authentication);
    		chain.doFilter(request, response);
            return ;
        }
        //do something
    	request.setAttribute(FILTER_APPLIED,true);
    	
//    	String [] allowDomain= {"http://127.0.0.1:8001", "http://xiaomagege.leanapp.cn", "http://localhost:8001","http://localhost:8080","http://localhost:8100","http://39.104.143.104","http://39.104.143.104:8080"};
//        Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain)); 
        String originHeader= request.getHeader("Origin");
        
//        if (allowedOrigins.contains(originHeader)){
//        	HttpServletResponse resp = (HttpServletResponse)response;
        	response.setHeader("Access-Control-Allow-Origin",originHeader);  
        	response.setHeader("Access-Control-Allow-Credentials", "true");  
        	response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");  
        	response.setHeader("Access-Control-Max-Age", "3600");  
        	response.setHeader("Access-Control-Allow-Headers", HeaderConstants.X_REQUESTED_WITH+","+HeaderConstants.AUTHORIZATION+","+HeaderConstants.CONTENT_TYPE);
//        }
    	
    	HttpServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request); 
    	String body = HttpHelper.getBodyString(requestWrapper);
    	log.info("---------->-------method+uri信息:{}+{},body信息:\n{}",request.getMethod(),request.getRequestURI(),JsonFormatUtil.formatConsoleJson(body));
    	UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(null, null, new ArrayList<SimpleGrantedAuthority>());
		SecurityContextHolder.getContext().setAuthentication(authentication);
    	chain.doFilter(requestWrapper, response);
    	
    	
    	/*JsonObjectResult resultInfo = new JsonObjectResult();
    	if(Init.isNoValidateInterface(request) || WhiteInterfaceEnum.isInWriteList(request)) {
			log.info("不用登录的接口");
			chain.doFilter(requestWrapper, response);
			return;
		}else {
			OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
			PrintWriter writer = null;
			String sessionId = CookieUtils.getCookie(request,"sessionId");
			//app验证
			String appSession = CookieUtils.getCookie(request,"appSession");
			if (sessionId == null || appSession==null) {
				writer = new PrintWriter(osw, true);
				resultInfo.setMessage("session为空");
				resultInfo.setCode(2);
				String jsonStr = JSON.toJSONString(resultInfo);
				writer.write(jsonStr);
				writer.flush();
				writer.close();
				osw.close();
				return;
			}
			//app验证
			if(appSession!=null) {
				chain.doFilter(requestWrapper, response);
			}
			Session dbSession = loginMapper.findBySessionId(sessionId);
			if (dbSession != null) {
				if (dbSession.getValidity().getTime() > new Date().getTime()) {
					chain.doFilter(request, response);
				} else {
					writer = new PrintWriter(osw, true);
					resultInfo.setMessage("session过期");
					resultInfo.setCode(2);
					String jsonStr = JSON.toJSONString(resultInfo);
					writer.write(jsonStr);
					writer.flush();
					writer.close();
					osw.close();
				}
			}else {
				writer = new PrintWriter(osw, true);
				resultInfo.setMessage("session为空");
				resultInfo.setCode(2);
				String jsonStr = JSON.toJSONString(resultInfo);
				writer.write(jsonStr);
				writer.flush();
				writer.close();
				osw.close();
			}
		}*/
    }
    	
    	
}  